<template>
  <div class="page h-min-screen overflow-hidden">
    <a-row :gutter="[0,0]">
      <a-col :span="5" :bordered="false" class="h-screen">
        <!-- 纸张设置 -->
        <p class="text-center mt-4">模板尺寸</p>
        <a-space class="w-full h-full overflow-y-scroll" direction="vertical" align="center" size="large">
          <div class="relative flex align-center justify-center bordered border-dotted border-gray-400" style="width: 120px;" v-for="(value,type) in paperTypes" :style="{height: value.height*1.5+'px'}" @click="setPaper(type, value)">
            <span>{{value.name}}</span>
            <span class="absolute h-full flex-row align-center justify-center" style="right: -1.5rem;">
              <span class="bg-white p-2">{{value.height}}</span>
            </span>
            <span class="absolute w-full flex-row align-center justify-center" style="bottom: -1.5rem;">
              <span class="bg-white p-2">{{value.width}}</span>
            </span>
          </div>

          <a-popover v-model="paperPopVisible" title="设置纸张宽高(mm)" trigger="click" placement="right">
            <div slot="content">
              <a-input-group compact style="margin: 10px 10px">
                <a-input type="number" v-model="paperWidth" style=" width: 100px; text-align: center"
                         placeholder="宽(mm)"/>
                <a-input style=" width: 30px; border-left: 0; pointer-events: none; backgroundColor: #fff"
                         placeholder="~" disabled
                />
                <a-input type="number" v-model="paperHeight" style="width: 100px; text-align: center; border-left: 0"
                         placeholder="高(mm)"/>
              </a-input-group>
              <a-button type="primary" style="width: 100%" @click="otherPaper">确定</a-button>
            </div>
            <div class="relative flex align-center justify-center bordered border-dotted border-gray-400" style="width: 120px; height: 135px" :class="{'primary': 'other'==curPaperType}">
              <span>自定义模板</span>
            </div>
          </a-popover>
          <p>&nbsp;</p>
          <p>&nbsp;</p>
        </a-space>
      </a-col>
      <a-col :span="12" class="relative h-screen bordered">
        <a-card class="card-design flex-row justify-center" :bordered="false">
          <div id="hiprint-printTemplate" class="hiprint-printTemplate" @click="changeTab('tab_2')"></div>
        </a-card>

        <div class="absolute print-btn-group w-full flex-col align-center justify-center mt-4">
          <a-space :size="'large'" class="w-full flex-row align-center justify-center">
          <!-- 保存/清空 -->
            <a-button type="primary" icon="save" @click="save">
              保存
            </a-button>
            <a-popconfirm
                title="是否确认清空?"
                okType="danger"
                okText="确定清空"
                @confirm="clearPaper"
            >
              <a-icon slot="icon" type="question-circle-o" style="color: red"/>
              <a-button type="danger">
                清空
                <a-icon type="close"/>
              </a-button>
            </a-popconfirm>
          <!-- 预览/打印 -->

<!--            <a-button type="default" icon="eye" @click="preView">签到页面设置</a-button>-->
            <a-button type="default" icon="eye" @click="preView">预览</a-button>
            <a-button type="default" @click="print">
              直接打印
              <a-icon type="printer"/>
            </a-button>
          <!--
          <a-button type="text" icon="zoom-out" @click="changeScale(false)"></a-button>
          <a-input-number
              :value="scaleValue"
              :min="scaleMin"
              :max="scaleMax"
              :step="0.1"
              disabled
              style="width: 70px;"
              :formatter="value => `${(value * 100).toFixed(0)}%`"
              :parser="value => value.replace('%', '')"
          />
          <a-button type="text" icon="zoom-in" @click="changeScale(true)"></a-button>
          -->
<!--          <json-view :template="template"/>-->
          </a-space>
          <div class="w-full flex-row align-center justify-center mt-4">
            <a-checkbox @change="onChange" :checked="isauto">是否自动打印</a-checkbox>
          </div>
        </div>
      </a-col>
      <a-col :span="7" class="params_setting_container h-screen">
        <a-tabs defaultActiveKey="tab_1" :activeKey="tabValue" @change="changeTab" type="line" class="h-full">
          <a-tab-pane key="tab_1" tab="基本设置" :forceRender="true">
            <a-row>
              <a-col :span="20" :offset="2" class="rect-printElement-types hiprintEpContainer">
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="tab_2" tab="属性设置" :forceRender="true">
            <a-row class="hinnn-layout-sider h-screen overflow-y-scroll">
              <div id="PrintElementOptionSetting"></div>
              <p>&nbsp;</p>
              <p>&nbsp;</p>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </a-col>
    </a-row>
    <!-- 预览 -->
    <print-preview ref="preView"/>
  </div>
</template>

<script>

import printPreview from './preview'
import jsonView from '../json-view.vue'

import {hiprint} from '../../index'
import {aProvider} from './providers'

let hiprintTemplate;
export default {
  name: "printCustom",
  components: {printPreview, jsonView},
  data() {
    return {
      template: null,
      // 模板选择
      mode: 0,
      modeList: [],
      // 当前纸张
      curPaper: {
        type: 'other',
        width: 60,
        height: 90
      },
      // 纸张类型
      paperTypes: {
        // 'A3': {
        //   width: 420,
        //   height: 296.6
        // },
        // 'A4': {
        //   width: 210,
        //   height: 296.6
        // },
        // 'A5': {
        //   width: 210,
        //   height: 147.6
        // },
        // 'B3': {
        //   width: 500,
        //   height: 352.6
        // },
        // 'B4': {
        //   width: 250,
        //   height: 352.6
        // },
        // 'B5': {
        //   width: 250,
        //   height: 175.6
        // }
        T1: {
          width: 60,
          height: 40,
          name: '模板一'
        },
        T2: {
          width: 60,
          height: 90,
          name: '模板二'
        }
      },
      scaleValue: 1,
      scaleMax: 5,
      scaleMin: 0.5,
      // 自定义纸张
      paperPopVisible: false,
      paperWidth: '60',
      paperHeight: '90',
      lastjson: '',
      tabValue: 'tab_1',
      id: 0,
      provider: {},
      baseUrl: '',
      urls: {
        getform: '/manage.php/print_setting/form',
        save: '/manage.php/print_setting/save'
      },
      formdata: null,
      printData: {},
      isauto: false, // 是否自动打印设置
    }
  },
  created() {
    if (location.hostname == 'localhost') {
      this.baseUrl = 'http://10.211.55.7:8586';
    } else {
      this.baseUrl = ''
    }
    console.log('created')
    this.id = this.getParamsByKey('id')
    this.getPrintSetting();
    // this.init()
  },
  computed: {
    curPaperType() {
      let type = 'other'
      let types = this.paperTypes
      for (const key in types) {
        let item = types[key]
        let {width, height} = this.curPaper
        if (item.width === width && item.height === height) {
          type = key
        }
      }
      return type
    }
  },
  mounted() {
    console.log('mounted')
  },
  methods: {
    onChange(e) {
      this.isauto = e.target.checked;
    },
    getParamsByKey(key) {
      let url = location.href;
      let queryInfo = url.split('?')[1];
      let queryParams = new URLSearchParams('?'+queryInfo);
      return queryParams.get(key) || 0;
    },
    changeTab(activeKey) {
      console.log(`${activeKey}`)
      this.tabValue = `${activeKey}`
    },
    init() {
      // this.modeList = providers.map((e) => {
      //   return {type: e.type, name: e.name, value: e.value}
      // })
      this.changeMode()
    },
    selectAll(){
      this.template.selectAllElements()
    },
    getPrintSetting() {
      var that = this;
      $.ajax({
        url: this.baseUrl+this.urls.getform,
        data: {
          id: this.id
        },
        dataType: 'GET',
        // type: 'JSON',
        async: true,
        complete(res) {
          let response = JSON.parse(res.responseText);
          if (response.code == 0) {
            that.provider = {
              name: '表单打印设置',
              type: 1,
              value: "aProviderModule",
              f: aProvider(response?.data?.provider)
            }
            that.formdata = response?.data?.data;
            let printData = {};
            (response?.data?.provider).forEach(item => {
              printData[item.fields] = item.testData;
            })
            that.isauto = response?.data?.data?.isauto === 1; // 是否自动打印设置
            that.printData = printData;
            that.changeMode()
          } else {
            that.$message.error(response.msg || '网络错误');
          }
        },
        failure: function (err) {
          that.$message.error(err.msg || '网络错误');
        }
      })
    },
    changeMode() {
      var _this = this;
      // let {mode} = this
      // let provider = providers[mode]
      let provider = this.provider; //getPrintSetting()
      hiprint.init({
        providers: [provider.f]
      });
      $('.hiprintEpContainer').empty()
      hiprint.PrintElementTypeManager.build('.hiprintEpContainer', provider.value);
      $('#hiprint-printTemplate').empty()
      let templates = null;
      try {
        if (this.formdata.user_qrcode) {
          templates = JSON.parse(this.formdata.user_qrcode);
          this.curPaper = {type: 'other', width: templates['aProviderModule']['panels'][0]['width'], height: templates['aProviderModule']['panels'][0]['height']}
          this.paperWidth = this.curPaper.width;
          this.paperHeight = this.curPaper.height;
        }
      } catch (e) {
        //
      }
      if (!templates) {
        templates = this.$ls.get('KEY_TEMPLATES', {"aProviderModule": {"panels": [
              {
                "index": 0,
                "name": (this.formdata.name || '打印表单')+'配置',
                "panelPageRule": "none",
                "paperNumberDisabled": true
              }
            ]}})
      }
      let template = templates[provider.value] ? templates[provider.value] : {}
      if (template) {
        template['panels'][0]['paperNumberDisabled'] = true;
      }
      this.template = hiprintTemplate = new hiprint.PrintTemplate({
        template: template,
        dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
        history: false, // 是否需要 撤销重做功能
        onDataChanged: (type, json) => {
          console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
          console.log(json); // 返回 template
          // 更新模板
          // hiprintTemplate.update(json)
          // console.log(hiprintTemplate.historyList)
        },
        // 图片选择功能
        onImageChooseClick: (target) => {
          // console.warn('图片选择', target);
          const input = document.createElement('input');
          input.setAttribute('type', 'file');
          // 将input添加到DOM（某些浏览器需要）
          input.style.display = 'none';
          input.setAttribute('accept', 'image/*'); // 仅允许选择图片文件
          document.body.appendChild(input);
          input.click();

          input.addEventListener('change', function () {
            const file = this.files[0];
            if (!file) {
              if (document.body.contains(input)) {
                document.body.removeChild(input);
              }
              return;
            };

            // 校验文件类型
            if (!file.type.startsWith('image/')) {
              _this.$message.error('请选择图片文件（支持jpg、png、webp等格式）')
              if (document.body.contains(input)) {
                document.body.removeChild(input);
              }
              return;
            }
            // 文件大小限制（可选）
            const maxSize = 10 * 1024 * 1024; // 10MB
            if (file.size > maxSize) {
              _this.$message.error('文件大小不能超过10MB');
              if (document.body.contains(input)) {
                document.body.removeChild(input);
              }
              return;
            }

            // console.warn('图片文件', file);
            _this.$message.info('上传中...');
            // 准备FormData（若服务器要求multipart/form-data）
            const formData = new FormData();
            formData.append('file', file); // 字段名'file'需与服务器保持一致

            fetch(_this.baseUrl+'/addons/csmsignin/indexajax/upload', {
              method: 'POST',
              body: formData, // 或使用file（直接二进制），根据服务器要求选择
            })
                .then(async (response) => {
                  if (!response.ok) {
                    // throw new Error(
                    //     `上传失败：${response.status} ${response.statusText}`,
                    // );
                    _this.$message.error(`上传失败: ${response.status} ${response.statusText}`)
                  }
                  return response.json();
                })
                .then((data) => {
                  // console.warn('上传成功', data.data);
                  // 转换成base64
                  // ImageBasePrintApi(data.data.fileName).then((resl) => {
                  //   console.warn('返回base64', resl);
                  //   if (resl.data) {
                  //     target.refresh(resl.data); // 将图片base64替换
                  //   }
                  // });
                  // 假设服务器返回{ url: "xxx" }，更新图片显示
                  if (data.data.fullurl) {
                    target.refresh(data.data.fullurl); // 根据实际需求调用刷新方法
                  }
                })
                .catch((error) => {
                  // console.error('上传失败', error);
                  _this.$message.error(`上传失败: ${error}`)
                })
                .finally(() => {
                  if (document.body.contains(input)) {
                    document.body.removeChild(input);
                  }
                });
          });
          // 处理取消选择文件的情况
          input.addEventListener('cancel', () => {
            setTimeout(() => {
              if (document.body.contains(input)) {
                document.body.removeChild(input);
              }
            }, 100);
          });
        },
        settingContainer: '#PrintElementOptionSetting',
        paginationContainer: '.hiprint-printPagination'
      });
      hiprintTemplate.design('#hiprint-printTemplate');
      // 获取当前放大比例, 当zoom时传true 才会有
      this.scaleValue = hiprintTemplate.editingPanel.scale || 1;
      this.otherPaper()
    },
    /**
     * 设置纸张大小
     * @param type [A3, A4, A5, B3, B4, B5, other]
     * @param value {width,height} mm
     */
    setPaper(type, value) {
      try {
        if (Object.keys(this.paperTypes).includes(type)) {
          this.curPaper = {type: type, width: value.width, height: value.height}
          hiprintTemplate.setPaper(value.width, value.height)
        } else {
          this.curPaper = {type: 'other', width: value.width, height: value.height}
          hiprintTemplate.setPaper(value.width, value.height)
        }
      } catch (error) {
        this.$message.error(`操作失败: ${error}`)
      }
    },
    changeScale(big) {
      let scaleValue = this.scaleValue;
      if (big) {
        scaleValue += 0.1;
        if (scaleValue > this.scaleMax) scaleValue = 5;
      } else {
        scaleValue -= 0.1;
        if (scaleValue < this.scaleMin) scaleValue = 0.5;
      }
      if (hiprintTemplate) {
        // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
        hiprintTemplate.zoom(scaleValue, true);
        this.scaleValue = scaleValue;
      }
    },
    otherPaper() {
      let value = {}
      value.width = this.paperWidth
      value.height = this.paperHeight
      this.paperPopVisible = false
      this.setPaper('other', value)
    },
    preView() {
      let {width} = this.curPaper;
      this.$refs.preView.show(hiprintTemplate, this.printData, width)
      // window.open(this.baseUrl+'/manage.php/csmsignin/confuser/signin?parentid='+this.id+'&mode=preview')
    },
    print() {
      if (window.hiwebSocket.opened) {
        const printerList = hiprintTemplate.getPrinterList();
        hiprintTemplate.print2(this.printData, {printer: '', title: '测试打印'});
        return
      }
      this.$error({
        title: "客户端未连接",
        content: (h) => (
          <div>
            客户端连接失败！
            <br />
            请确保客户端已下载，并
            <a href="hiprint://" target="_blank">运行</a>
            打印服务！
          </div>
        ),
      });
    },
    save() {
      // let {mode} = this
      let provider = this.provider; //providers[mode]
      this.setTemplate({
        name: provider.value,
        json: hiprintTemplate.getJson()
      })
    },
    setTemplate(payload) {
      let templates = this.$ls.get('KEY_TEMPLATES', {})
      templates[payload.name] = payload.json
      this.$ls.set('KEY_TEMPLATES', templates)
      var that = this;
      $.ajax({
        url: this.baseUrl+this.urls.save,
        data: {
          id: this.id,
          content: JSON.stringify(templates),
          isauto: this.isauto ? 1 : 0,
        },
        dataType: 'JSON',
        type: 'POST',
        complete(res) {
          that.$message.info('保存成功')
        },
        failure(error) {
          that.$message.error(error.msg || '保存失败')
        }
      })
    },
    clearPaper() {
      try {
        hiprintTemplate.clear();
      } catch (error) {
        this.$message.error(`操作失败: ${error}`);
      }
    }
  }
}
</script>

<style lang="less" scoped>
// build 拖拽

// 默认图片
/deep/ .hiprint-printElement-image-content {
  img {
    content: url("~@/assets/logo.png");
  }
}

// 设计容器
.card-design {
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
}
/deep/ .ant-tabs-nav{
  justify-content: center;
  align-items: center;
  display: flex;
}
/deep/ .ant-tabs-ink-bar {
  left: 50%;
  margin-left: -104px;
}
@media screen and (max-width: 576px){
  /deep/ .ant-tabs-nav{
    justify-content: center;
    align-items: center;
    display: block!important;
  }
}
/deep/ .hiprint-printElement-type {
  margin-bottom: 12px;
}
/deep/ .hiprint-printElement-type > li > ul > li {
  width: 100%;
  float: unset;
  max-width: 100%;
}
/deep/ .hiprint-printElement-type > li > ul > li > a {
  position: relative;
  top: 0!important;
  padding: 4px 4% 4px 12%;
  color: #999;
  line-height: 1.5;
  height: auto;
  text-overflow: ellipsis;
  box-shadow: unset;
  border-radius: 2px;
  border-color: #222222;
  display: block;
  width: 84%;
  max-width: 100%;
  text-align: left;
  margin-bottom: 12px;
}
/deep/ .hiprint-printElement-type > li > ul > li > a::before {
  position: absolute;
  content: "+";
  color: #5cb85c;
  font-size: 20px;
  font-weight: bold;
  left: 10px;
  top: -2px;
}
/deep/ .hiprint-printElement-type > li > .title {
  color: #000000;
}
#PrintElementOptionSetting {
  padding: 0 12px;
}
.hidden {
  display: none;
}
/deep/ .hiprint-option-items .hiprint-option-item-field input, /deep/ .hiprint-option-items .hiprint-option-item-field select, /deep/ .hiprint-option-items .hiprint-option-item-field textarea {
  padding: 5px 3px;
  height: auto;
  border-color: #e8e8e8;
}
/deep/ .hiprint-option-item-settingBtn {
  height: 24pt;
  line-height: 24pt;
}
/deep/ .hiprint-printElement-type > li > ul > li > a[tid='aProviderModule.bg'] {
  height: 40pt;
  display: flex;
  align-items: center;
}
/deep/ .hiprint-printElement-type > li > ul > li > a[tid='aProviderModule.bg']::before {
  top: 7pt;
}
.print-btn-group {
  bottom: 60px;
}
</style>
